package com.swak.vertx.protocol.http.adapter;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

public class InvokeAdapter extends AbstractAdapter {

	@Override
	@SuppressWarnings("unchecked")
	public CompletionStage<Context> handle(Context context) {
		try {
			Object result = context.$method.doInvoke((Object[]) context.$result);
			if (result != null && result instanceof CompletionStage) {
				CompletionStage<Object> resultFuture = (CompletionStage<Object>) result;
				return resultFuture.thenCompose(res -> {
					context.$result = res;
					return this.next(context);
				}).exceptionally(e -> {
					context.$error = e;
					return context;
				});
			}
			context.$result = result;
			return this.next(context);
		} catch (Throwable e) {
			CompletableFuture<Context> future = new CompletableFuture<Context>();
			future.completeExceptionally(e);
			return future.exceptionally(ex -> {
				context.$error = ex;
				return context;
			});
		}
	}
}
